﻿/*
版权所有：版权所有(C) 2011，刘建新
文件编号：M01_LeaveMsgMgntBll.cs
文件名称：LeaveMsgMgntBll.cs
系统编号：Z0003007
系统名称：通用办公系统
模块编号：M01
模块名称：信息发布
设计文档：IOA_M01信息发布XDE建模.mdx
完成日期：2011-01-06
作　　者：
内容摘要：表[Leave_msg_Mgnt]业务操作类
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Eis51.CampanyCMS.Model.Bus;
using Eis51.CampanyCMS.FrameWork;
using Eis51.CampanyCMS.Model.Bus.QueryO;
using System.Data;
using Eis51.CampanyCMS.Access.Bus;
using System.Collections;

namespace Eis51.CampanyCMS.Business.Bus
{
    /// <summary>
	/// LeaveMsgMgnt的BLL 自定义方法
	/// 该BLL已经生成了基本的业务操作，在自动生成的方法中已经提供了事务机制
	/// </summary>
    public partial class LeaveMsgMgntBLL : BaseBLL<LeaveMsgMgnt>
    {
        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public bool Submit(LeaveMsgMgnt obj)
        {

            //修改答复的创建时间
            if (obj.ParentId != 0)
            {
                LeaveMsgMgnt parent = this.Get(new LeaveMsgMgnt.Key(obj.ParentId));
                if (parent != null)
                {
                    obj.CreateDate = parent.CreateDate;
                }
            }

            if (obj.MsgId > 0)
            {
                this.Update(obj);
            }
            else
            {
                obj.IsViewed = 0;
                int i = this.Insert(obj);
                //更新Mainid=0 则更新Mainid=MsgId ；
                if (i > 0)
                {
                    if (obj.Mainid <= 0)
                    {
                        obj.Mainid = obj.MsgId;
                        obj.ParentId = 0;
                    }
                    else
                    {
                        if (obj.ParentId == 0)
                        {
                            obj.ParentId = GetMsgIdByMainid(obj.Mainid);
                        }
                    }
                    this.Update(obj);
                }
            }
            return true;
        }

        /// <summary>
        /// 获取留言信息
        /// </summary>
        /// <param name="keyType"></param>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        public List<LeaveMsgMgnt> GetLeaveMsgs(LeaveMsgKeyType keyType, string keyValue)
        {
            string sql = string.Format("select * from Leave_msg_Mgnt where Key_Type='{0}' ",
                        keyType.ToString("d"));
            if (keyValue != string.Empty)
            {
                sql += string.Format(" and Key_Value='{0}'", keyValue);
            }

            sql += "order by Create_Date desc,Msg_ID asc";
            DataTable dt = this.GetDataTable(sql);

            return LeaveMsgMgnt.Dt2Objs(dt) as List<LeaveMsgMgnt>;
        }


        /// <summary>
        /// 获取留言信息
        /// </summary>
        /// <param name="keyType"></param>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        public LeaveMsgMgnt GetMainLeaveMsgs(int MainId)
        {
            string sql = string.Format("select * from Leave_msg_Mgnt where MainId={0} ", MainId);
            sql += " and Parent_ID=0 ";
            DataTable dt = this.GetDataTable(sql);
            if (dt == null || dt.Rows.Count <= 0)
                return null;
            return LeaveMsgMgnt.Dr2Obj(dt.Rows[0]);
        }


        public string GetMsgsHtml(LeaveMsgKeyType keyType, string keyValue)
        {
            List<LeaveMsgMgnt> lst = GetLeaveMsgs(keyType, keyValue);
            StringBuilder sb = new StringBuilder();
            int curParentID = 0;
            foreach (LeaveMsgMgnt tmp in lst)
            {
                if (tmp.ParentId != 0)
                {
                    if (curParentID == 0)
                    {
                        sb.Append("<div class='divReply'>");
                    }
                    sb.AppendFormat("【{0} {1}:】", tmp.CreateBy, tmp.CreateDate.ToString("yyyy-MM-dd HH:mm"));
                    sb.Append("<BR>");
                    sb.Append(tmp.MsgContent);
                    sb.Append("<BR>");
                    sb.Append("<BR>");
                }
                else
                {
                    if (curParentID != 0)
                    {
                        sb.Append("</div>");          //结束                        
                    }
                    sb.AppendFormat("【{0} {1}:】<a href=\"#\" onclick=\"Replayto('{2}')\">回复</a>", tmp.CreateBy, tmp.CreateDate.ToString("yyyy-MM-dd HH:mm"), tmp.MsgId);
                    sb.Append("<BR>");
                    sb.Append(tmp.MsgContent);
                    sb.Append("<BR>");
                    sb.Append("<BR>");

                }
                curParentID = tmp.ParentId;
            }
            return sb.ToString();
        }

        public DataTable SearchData(LeaveMsgMgntQuery q)
        {
            string sql = string.Format("select * from Leave_msg_Mgnt where  (parent_id={0} or -1={0})  ", q.parent_id);
            if (q.UserName != string.Empty)
            {
                sql += string.Format(" and ( CREATE_BY='{0}' OR RECEIVER_ID ='{0}')  ", q.UserName);
            }
            if (q.KeyType != string.Empty)
            {
                sql += string.Format(" and Key_Type='{0}' ", q.KeyType);
            }
            if (q.KeyValue != string.Empty)
            {
                sql += string.Format(" and Key_Value='{0}' ", q.KeyValue);
            }
            if (q.Mainid > 0)
            {
                sql += string.Format(" and Mainid={0} ", q.Mainid);
            }

            if (q.havenews > 0)
            {
                sql += string.Format(" and (havenews={0}  or havenews=3)", q.havenews);
            }
            else if (q.havenews == 0)
            {
                //如果是卖家 havenews=2也表示未阅，如果是买家havenews=1也表示未阅
                sql += string.Format(" and (havenews={0} or havenews={1})", q.havenews, q.IsSeller ? LeaveMsgHaveNew.BuyerHaveNew.ToString("d") : LeaveMsgHaveNew.SellerHaveNew.ToString("d"));
            }


            sql += "order by Msg_ID desc";
            DataTable dt = this.GetDataTable(sql);
            return dt;
        }





        public int ReplyCount(int Mainid)
        {
            string sql = string.Format("select * from Leave_msg_Mgnt where Mainid={0}  ", Mainid);
            DataTable dt = this.GetDataTable(sql);
            if (dt != null && dt.Rows.Count > 0)
            {
                return dt.Rows.Count - 1;
            }
            return 0;
        }


        public void IsView(int Mainid, string UserName)
        {
            string sql = "UPDATE LEAVE_MSG_MGNT SET IS_VIEWED=1 WHERE Mainid={0} and RECEIVER_ID='{1}'";
            sql = string.Format(sql, Mainid, UserName);
           this.Execute(sql);
        }

        public string GetNewMsgCount(string UserName, string KeyType)
        {
            string sql = "select count(*) as Tcount  from   LEAVE_MSG_MGNT where parent_id =0 and (create_by='{0}' or Receiver_id='{0}') and (havenews=3 or havenews={1}) and (key_type='{2}' or '{2}'='') ";
            sql = string.Format(sql, UserName, (int)LeaveMsgHaveNew.SellerHaveNew, KeyType);
            DataTable dt = this.GetDataTable(sql);
            return dt.Rows[0]["Tcount"].ToString();
        }

        /// <summary>
        /// 通过主信息ID删除所有的相关回复记录
        /// </summary>
        /// <param name="MsgId"></param>
        public void Delete(int Msg_ID)
        {
            string sql = string.Format("DELETE from  LEAVE_MSG_MGNT WHERE   MainId in (select MainId from LEAVE_MSG_MGNT  where Msg_ID={0} ) ", Msg_ID);
            this.Execute(sql);
        }

        /// <summary>
        /// 通过 keytype，Keyvalue 获得主信息ID
        /// </summary>
        /// <param name="keytype"></param>
        /// <param name="Keyvalue"></param>
        /// <returns></returns>
        public int GetMsgIdByMainid(int Mainid)
        {
            string sql = "select Msg_ID from Leave_msg_Mgnt where   Mainid={0} and Parent_ID=0";
            sql = string.Format(sql, Mainid);
            DataTable dt = this.GetDataTable(sql);
            if (dt != null && dt.Rows.Count > 0)
            {
                return int.Parse(dt.Rows[0]["Msg_ID"].ToString());
            }
            return 0;
        }

        /// <summary>
        /// 获得卖家的ID
        /// </summary>
        /// <param name="Key_Value"></param>
        /// <param name="MsgKeyType"></param>
        /// <returns></returns>
        public string GetSelleridByValue(string Key_Value, LeaveMsgKeyType MsgKeyType)
        {
            string Sellerid = "";
            if (MsgKeyType == LeaveMsgKeyType.Order)
            {
                Sellerid = OrderApplyBLL.GetInstance().GetSellerByOrderid(Key_Value);
            }
            if (MsgKeyType == LeaveMsgKeyType.Product)
            {
                Products product = ProductsBLL.GetInstance().Get(new Products.Key(int.Parse(Key_Value)));
                if (product != null)
                {
                    Sellerid = product.Createby;
                }
            }
            return Sellerid;
        }

        /// <summary>
        /// 获得买家的ID
        /// </summary>
        /// <param name="Key_Value"></param>
        /// <param name="MsgKeyType"></param>
        /// <param name="Sellerid"></param>
        /// <returns></returns>
        public string GetBuyeridByValue(int Mainid, string Sellerid)
        {
            string sql = @" select receiver_id  as buyerid from Leave_msg_Mgnt where create_by='{1}' and Mainid={0}
                           union  select create_by  as buyerid   from Leave_msg_Mgnt where receiver_id='{1}' and Mainid={0}  ";
            sql = string.Format(sql, Mainid, Sellerid);
            DataTable dt = this.GetDataTable(sql);
            if (dt != null && dt.Rows.Count > 0)
            {
                return dt.Rows[0]["buyerid"].ToString();
            }
            return "";
        }


        /// <summary>
        /// 更新主信息，是否有卖家或者买家的新信息！
        /// </summary>
        /// <param name="Key_Value"></param>
        /// <param name="Key_type"></param>
        /// <param name="havnew"></param>
        public void MainMsgIsNew(int Mainid, LeaveMsgHaveNew havnew)
        {
            LeaveMsgMgnt leavemsgmgnt = GetMainLeaveMsgs(Mainid);
            if (leavemsgmgnt.Havenews != (int)havnew && leavemsgmgnt.Havenews > 0)
            {
                leavemsgmgnt.Havenews = (int)LeaveMsgHaveNew.AllNew;
            }
            else if (leavemsgmgnt.Havenews <= 0)
            {
                leavemsgmgnt.Havenews = (int)havnew;
            }
            else
            {
                //不用更新，直接返回！
                return;
            }
            this.Update(leavemsgmgnt);
        }

        public void MainMsgIsViewed(int Mainid, LeaveMsgHaveNew havnew)
        {
            LeaveMsgMgnt leavemsgmgnt = GetMainLeaveMsgs(Mainid);
            if (leavemsgmgnt.Havenews == (int)havnew)
            {
                leavemsgmgnt.Havenews = (int)LeaveMsgHaveNew.NoBodyNew;
            }
            else if (leavemsgmgnt.Havenews == (int)LeaveMsgHaveNew.AllNew)
            {
                if (havnew == LeaveMsgHaveNew.BuyerHaveNew)
                {
                    leavemsgmgnt.Havenews = (int)LeaveMsgHaveNew.SellerHaveNew;
                }
                else
                {
                    leavemsgmgnt.Havenews = (int)LeaveMsgHaveNew.BuyerHaveNew;
                }
            }
            else
            {
                //不用更新，直接返回！
                return;
            }
            this.Update(leavemsgmgnt);
        }

        public string GetLeaveMsgTypeCnName(string keyType)
        {
            if (keyType == LeaveMsgKeyType.Order.ToString("d"))
            {
                return "订单留言";
            }
            else if (keyType == LeaveMsgKeyType.Product.ToString("d"))
            {
                return "产品留言";
            }
            else
            {
                return "系统";
            }
        }


        public string GetLeaveMsgTypeEnName(string keyType)
        {
            if (keyType == LeaveMsgKeyType.Order.ToString("d"))
            {
                return "Order  ";
            }
            else if (keyType == LeaveMsgKeyType.Product.ToString("d"))
            {
                return "Product";
            }
            else
            {
                return "System";
            }
        }
    }


    #region 代码自动生成
    /// <summary>
    /// LeaveMsgMgnt的BLL
    /// 该BLL已经生成了基本的业务操作，在自动生成的方法中已经提供了事务机制
    /// </summary>
    public partial class LeaveMsgMgntBLL : BaseBLL<LeaveMsgMgnt>
    {
        #region 自动生成代码：取得相关实体

        /// <summary>
        /// 方法名称: LeaveMsgMgntBLL
        /// 内容摘要: 构造函数进行初始化
        /// </summary>
        protected LeaveMsgMgntBLL()
        {
        }
        private static volatile LeaveMsgMgntBLL m_instance = null;
        /// <summary>
        /// 方法名称: GetInstance
        /// 内容摘要: 取得 LeaveMsgMgntBLL 对象
        /// </summary>
        /// <returns>返回一个已经存在的实体</returns>
        public static LeaveMsgMgntBLL GetInstance()
        {
            // 通用的必要代码 iBatisNet双校检机制,如果实例不存在
            if (m_instance == null)
            {
                lock (typeof(LeaveMsgMgntBLL))
                {

                    // 如果实例不存在
                    if (m_instance == null)
                    {

                        // 创建一个的实例
                        m_instance = new LeaveMsgMgntBLL();
                    }
                }
            }

            // 返回业务逻辑对象
            return m_instance;
        }

        #endregion

        #region 自动生成代码：基本业务公开函数

        /// <summary>
        /// 方法名称: Get
        /// 内容摘要: 由键值获取一个实体对象
        /// </summary>
        /// <returns>LeaveMsgMgnt</returns>
        public LeaveMsgMgnt Get(LeaveMsgMgnt.Key key)
        {

            return LeaveMsgMgntDao.GetInstance().SelectByID(key);
        }
        /// <summary>
        /// 方法名称: Select
        /// 内容摘要: 基本查询，不带任何条件的查询
        /// </summary>
        public IList Select()
        {
            return LeaveMsgMgntDao.GetInstance().SelectAll();
        }
        /// <summary>
        /// 方法名称: Insert
        /// 内容摘要: 插入一条新纪录
        /// </summary>
        /// <returns>int</returns>
        public int Insert(LeaveMsgMgnt obj)
        {
            int result = 0;
            try
            {
                result = LeaveMsgMgntDao.GetInstance().Insert(obj);
            }
            catch (Exception e)
            {
                throw e;
            }
            return result;
        }

        /// <summary>
        /// 方法名称: Update
        /// 内容摘要: 更新一条新纪录
        /// </summary>
        /// <returns>int</returns>
        public int Update(LeaveMsgMgnt obj)
        {
            LeaveMsgMgntDao.GetInstance().Update(obj);
            return 1;
        }

        /// <summary>
        /// 方法名称: Delete
        /// 内容摘要: 删除一条新纪录
        /// </summary>
        /// <returns>int</returns>
        public int Delete(LeaveMsgMgnt obj)
        {
            bool result = LeaveMsgMgntDao.GetInstance().DeleteByID(new LeaveMsgMgnt.Key(obj.Mainid));
            return result ? 1 : 0;
        }

        #endregion

    }
    #endregion
}